package com.shuql.cloud.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 请求资源前, 先通过此过滤器进行用户令牌解析与校验、转发
 *
 * @author ：shuquanliang
 * @date ：Created in 2020/4/23 20:35
 * @description：
 */
@Component
public class AuthenticationFilter extends ZuulFilter {

    @Override
    public String filterType() {
        // pre 请求路由前调用
        return "pre";
    }

    @Override
    public int filterOrder() {
        //过滤器执行顺序, 数值越小优先级越高
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        //true 执行下面run方法
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        // 获取从Security上下文中获取认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //JWT令牌有效，则会解析用户信息封装到OAuth2Authentication对象中
        if (!(authentication instanceof OAuth2Authentication)) {
            return null;
        }

        //只是用户名, 用户表中手机号，邮箱等都没有
        Object principal = authentication.getPrincipal();
        //请求详情
        Object details = authentication.getDetails();
        //此用户拥有权限
        Set<String> authoritySet = AuthorityUtils.authorityListToSet(authentication.getAuthorities());

        //封装传输的数据
        Map<String, Object> result = new HashMap<>();
        result.put("principal", principal);
        result.put("details", details);
        result.put("authorities", authoritySet);

        //获取当前请求上下文
        RequestContext currentContext = RequestContext.getCurrentContext();
        String base64 = Base64Utils.encodeToString(JSON.toJSONString(result).getBytes());
        currentContext.addZuulRequestHeader("X-SHUQL-TOKEN", base64);
        currentContext.addZuulRequestHeader("X-SHUQL-USERNAME", (String) principal);

        return null;
    }
}
